<%@ page import="java.util.*" %>
<%@ page import="bw.note.NotebookManager" %>
<%
  String defaultNotebookPage = ( new NotebookManager() ).getDefaultPage(); 
%>
<html>
<head>
<title>notebook!</title>
<link rel=STYLESHEET type="text/css" href="style.jsp">
<link rel="SHORTCUT ICON" href="images/favicon.ico">

<!-- Sam Skin CSS -->
<link rel="stylesheet" type="text/css" href="include/yui_2.6/container-core.css">
 
<!-- Dependencies --> 
<script type="text/javascript" src="include/yui_2.6/yahoo-dom-event.js"></script>

<!-- OPTIONAL: Drag & Drop (only required if enabling Drag & Drop) --> 
<script type="text/javascript" src="include/yui_2.6/dragdrop-min.js"></script> 
 
<!-- Source file --> 
<script type="text/javascript" src="include/yui_2.6/container-min.js"></script>

<!-- Skin CSS file --> 
<link rel="stylesheet" type="text/css" href="include/yui_2.6/resize.css"> 
<!-- Utility Dependencies --> 
<script type="text/javascript" src="include/yui_2.6/element-beta-min.js"></script>  
<!-- Source file for the Resize Utility --> 
<script type="text/javascript" src="include/yui_2.6/resize-min.js"></script> 
<!-- Connect -->
<script type="text/javascript" src="include/yui_2.6/connection-min.js"></script>
<!-- Animate -->
<script type="text/javascript" src="include/yui_2.6/animation-min.js"></script> 

<!-- My Tiny Editor -->
<script type="text/javascript" src="include/tinyEditor.js"></script>

<!-- Sidebar -->
<script type="text/javascript" src="include/sidebar.js"></script>

<style>

.yui-panel {
		position:relative;
		border:none;
		overflow:visible;
		background-color:transparent;
	}

.yui-panel .hd { padding:5px 10px 5px 10px; 
                         background:#294766; 
                         font-weight:bold;
                         color: #FFFFFF; }

.yui-panel .bd { padding:5px 10px 5px 10px; text-align:left; color:#FFFFFF;
                 line-height:1.2; 
	         overflow:auto; 
                 font-weight:bold; background:#143D66; }

.yui-panel .ft { height:15px; 
 	         padding:0; 
                 background:#143D66; }

.yui-panel .container-close { 
	    position:absolute; 
	    top:3px; 
	    right:4px; 
	    height:18px; 
	    width:17px; 
	    background:#000000;
	} 

.yui-skin-sam .yui-resize .yui-resize-handle-br { 
	    right:0; 
	    bottom:0; 
	    height: 10px; 
	    width: 10px; 
	    position:absolute;  
	} 

.yui-skin-sam .yui-resize .yui-resize-handle { 
	    background-color: #143D66; 
            opacity: .5;
	} 

.yui-panel-container.matte{padding:2px; background-color:#003366;}

.editor { border:none; }

.saveNoteLink { visibility:hidden; }

</style>

</head>
<body style="overflow:hidden; background:#000033; margin:0px; padding:0px;"> 

<div id="notebookHolder" style="background:#003366; position:relative; width:100%; height:100%; z-index:2;">

<div id="pageNameHolder" class="notebookPageName">
<%= ( NotebookManager.DEFAULT_PAGE_NAME.equals( defaultNotebookPage ) ? "Page One" : defaultNotebookPage ) %>
</div>

<div class="supplementaryNav">
<a class="supnavlink" href="javascript:addNotebookEntry()">add note</a> |
<a class="supnavlink" href="javascript:sidebar.showSidebar( true )">show index</a>
</div>

<div id="container" class="yui-skin-sam"></div>

<jsp:include page="nav.html" />

</div>

<div id="notebookIndex" style="width:230px; position:absolute; top:0px; right:0px; z-index:1; padding:10px; color:#ffffff;">

<div style="padding-bottom:15px;">
<table width="100%" cellpadding="0" cellspacing="0" margin="0">
<tr><td><b>notebook index</b></td><td align="right"><a class="supnavlink" href="javascript:sidebar.showSidebar( false )">hide index</a></td></tr>
</table>
</div>

<div class="notebookIndexEntry">
<table width="100%" cellpadding="0" cellspacing="0" margin="0">
<tr><td><span id="indexIndicator_def" class="indexIndicator"><%= ( NotebookManager.DEFAULT_PAGE_NAME.equals( defaultNotebookPage ) ? "&#9658; " : "" ) %></span><a href="javascript:gotoPage( '<%= NotebookManager.DEFAULT_PAGE_NAME %>', 'def' )" class="notebookIndexLink">Page One</a></td><td align="right"></td></tr>
</table>
</div>

<div id="notebookPages"></div>

<div class="notebookIndexEntry">
<table width="100%" cellpadding="0" cellspacing="0" margin="0">
<tr><td colspan="2" align="right">
<div id="addNewPage"><a class="supnavlink" href="javascript:showNewPageField()">add new page</a></div>
</td></tr>
</table>
</div>

</div>

</body>

<script>

var sidebar = new Sidebar( 'notebookHolder' );

//default page
//var notebookPageName = 'NoteBookMain';
var notebookPageName = '<%= defaultNotebookPage %>';

var OverlayManager = new YAHOO.widget.OverlayManager(); 

var index = 0;

var addNewPageLink;

function showNewPageField ()
{
  var t = document.createElement( "input" );
  t.setAttribute( "type", "text" );
  t.setAttribute( "name", "pageName" );
  t.setAttribute( "maxlength", "25" );
  t.setAttribute( "style", "font-size:x-small; width:100%;" );
  t.setAttribute( "onKeyPress", "addNewPage(event,this)" );

  var c = document.getElementById( "addNewPage" );
  addNewPageLink = c.firstChild;
  c.replaceChild( t, c.firstChild );

  var b = document.createElement( "div" );
  b.setAttribute( "class", "cancelNewsSource" );

  var cancelLink = document.createElement( "a" );
  cancelLink.setAttribute( "href", "javascript:cancelAddNewPage()" );
  cancelLink.setAttribute( "class", "supnavlink" );
  cancelLink.appendChild( document.createTextNode( "Cancel" ) );

  b.appendChild( cancelLink );

  c.appendChild( b );

  t.focus();
}

function addNewPage ( evt, n )
{
  if ( evt.which == 13 ) {
    //alert( "adding index entry: " + n.value );

    var surl = 'notebook?action=addPage&name=' + escape( n.value );

    var callback = 
    {
      success : handleAddPage,
      failure : handleFailure
    };

    YAHOO.util.Connect.asyncRequest( 'GET', surl, callback );
  }
}

function handleAddPage ( obj )
{
  cancelAddNewPage();
  buildIndex( obj );
}

function cancelAddNewPage ()
{
  var c = document.getElementById( "addNewPage" );
  while ( c.hasChildNodes() ) { c.removeChild( c.firstChild ); }
  c.appendChild( addNewPageLink );
}

function deletePage ( page )
{
  var surl = 'notebook?action=deletePage&name=' + escape( page );

  var callback = 
  {
    success : handleDeletePage,
    failure : handleFailure,
    argument : [ page ]
  };

  YAHOO.util.Connect.asyncRequest( 'GET', surl, callback );
}

function handleDeletePage ( obj )
{
  buildIndex( obj );
  
  if ( obj.argument[0] == notebookPageName ) {
    gotoPage( '<%= NotebookManager.DEFAULT_PAGE_NAME %>', 'def' );
  }
}

function gotoPage ( page, ind )
{
  var surl = 'notebook?action=setDefaultPage&name=' + escape( page );

  var callback = 
  {
    success : handleGotoPage,
    failure : handleFailure,
    argument : [ page, ind ]
  };

  YAHOO.util.Connect.asyncRequest( 'GET', surl, callback );
}

function handleGotoPage ( obj )
{
  //remove current overlays
  var notes = OverlayManager.overlays;
  for ( var i = 0; i < notes.length; i++ )
  {
    OverlayManager.remove( notes[i] );
    notes[i].destroy();
  }

  //populate with new notes
  notebookPageName = obj.argument[0];

  if ( notebookPageName == '<%= NotebookManager.DEFAULT_PAGE_NAME %>' ) {
      document.getElementById( "pageNameHolder" ).innerHTML = 'Page One';
  }
  else {
    document.getElementById( "pageNameHolder" ).innerHTML = notebookPageName;
  }

  getNotebookEntries();

  //clear the page indictors
  var sps = ( new YAHOO.util.Element( "notebookIndex" ) ).getElementsByClassName( "indexIndicator" );
  for ( var i = 0; i < sps.length; i++ ) {
    sps[i].innerHTML = "";
  }

  //set the current page indicator
  var sp = document.getElementById( "indexIndicator_" + obj.argument[1] );
  sp.innerHTML = "&#9658; ";  
}

function getNotebookIndex ()
{
  var surl = 'notebook?action=list';

  var callback = 
  {
    success : buildIndex,
    failure : handleFailure
  };

  YAHOO.util.Connect.asyncRequest( 'GET', surl, callback );
}

function buildIndex ( obj )
{
  var doc = obj.responseXML;

  var pages = doc.getElementsByTagName( "page" );

  var pageDiv = document.getElementById( "notebookPages" );
  while ( pageDiv.hasChildNodes() ) { pageDiv.removeChild( pageDiv.firstChild ); }

  for ( var i = 0; i < pages.length; i++ ) {
    var name = pages.item( i ).getAttribute( "name" );
    var notesSize = pages.item( i ).getAttribute( "size" );
    
    var d = document.createElement( "DIV" );
    d.setAttribute( "class", "notebookIndexEntry" );

    var t = document.createElement( "TABLE" );
    t.setAttribute( "width", "100%" );
    t.setAttribute( "cellpadding", "0" );
    t.setAttribute( "cellspacing", "0" );
    t.setAttribute( "margin", "0" );
    
    var tr = document.createElement( "TR" );
    var td_name = document.createElement( "TD" );
    var sp = document.createElement( "SPAN" );
    sp.setAttribute( "id", "indexIndicator_" + i );    
    sp.setAttribute( "class", "indexIndicator" );

    if ( name == notebookPageName ) {
      sp.innerHTML = "&#9658; ";
    }
    
    td_name.appendChild( sp );

    var link = document.createElement( "A" );
    link.setAttribute( "class", "notebookIndexLink" );
    link.setAttribute( "href", "javascript:gotoPage( '" + name + "', '" + i + "' )" );
    link.appendChild( document.createTextNode( name ) );
    td_name.appendChild( link );

    var td_del = document.createElement( "TD" );
    td_del.setAttribute( "align", "right" );
    
    if ( notesSize == 0 ) {
      var del = document.createElement( "A" );
      del.setAttribute( "class", "supnavlink" );
      del.setAttribute( "href", "javascript:deletePage( '" + name + "' )" );
      del.appendChild( document.createTextNode( "delete" ) );
      td_del.appendChild( del );
    }

    tr.appendChild( td_name );
    tr.appendChild( td_del );

    t.appendChild( tr );

    d.appendChild( t );

    pageDiv.appendChild( d );
  }
}

function removeNote ( id )
{
  var entry = OverlayManager.find( id );
  var noteId = entry.element.getAttribute( "noteId" );

  if ( noteId == '' ) {
    entry.destroy();
    return;
  }

  var surl = 'note?action=delete&id=' + notebookPageName + '&noteId=' + noteId;

  var callback = 
  {
    success : handleDelete,
    failure : handleFailure,
    argument : id
  };

  YAHOO.util.Connect.asyncRequest( 'GET', surl, callback );
}

function handleDelete ( obj )
{
  var entry = OverlayManager.find( obj.argument );
  entry.destroy();
  
  if ( OverlayManager.overlays.length == 0 ) {
    getNotebookIndex();
  }
}

function getNotebookEntries ()
{
  var surl = 'note?action=getNotes&sortByLastMod=true&id=' + notebookPageName;

  var callback = 
  {
    success : parseNotebookDoc,
    failure : handleFailure
  };

  YAHOO.util.Connect.asyncRequest( 'GET', surl, callback );
}

function parseNotebookDoc ( obj )
{
  var doc = obj.responseXML;
  var notes = doc.getElementsByTagName( "note" );

  var indexOffset = ( sidebar.isSidebarOpen ? -250 : 0 );

  for ( var i = 0; i < notes.length; i++ ) {
    var noteId = notes.item( i ).getAttribute( "id" );
    var year = notes.item( i ).getAttribute( "year" );
    var month = notes.item( i ).getAttribute( "month" );
    var date = notes.item( i ).getAttribute( "date" );
    var time = notes.item( i ).getAttribute( "time" );
    var height = notes.item( i ).getAttribute( "height" );
    var width = notes.item( i ).getAttribute( "width" );
    var top = notes.item( i ).getAttribute( "top" );
    var left = Number( notes.item( i ).getAttribute( "left" ) ) + Number( indexOffset );
    var content = notes.item( i ).childNodes.item( 0 ).nodeValue;

    newNotebookEntry( noteId, formatDate( year, month, date, time ), 
                      height, width, top, left, content );
  }
}

function saveNote ( id )
{
  var note = OverlayManager.find( id );
  var region = YAHOO.util.Dom.getRegion( note.element );
  var left = region.left;
  var top = region.top;
  var width = region.right - region.left;
  var height = region.bottom - region.top;
  var year = note.element.getAttribute( "year" );
  var month = note.element.getAttribute( "month" );
  var date = note.element.getAttribute( "date" );
  var noteId = note.element.getAttribute( "noteId" );

  var editor = TinyEditor.getEditor( id + '_data' );
  var content = editor.getValue();

  var surl = 'note?action=save&id=' + notebookPageName +
             '&data=' + escape( content ) + '&noteId=' + noteId +
             '&year=' + year + '&month=' + month + '&date=' + date +
             '&width=' + width + '&height=' + height +
             '&top=' + top + '&left=' + left;

  var callback = 
  {
    success : handleSaveNote,
    failure : handleFailure,
    argument : id
  };

  YAHOO.util.Connect.asyncRequest( 'GET', surl, callback );
}

function handleSaveNote ( obj )
{
  //set the right note id for new saved note objects
  var note = OverlayManager.find( obj.argument );
  var noteId = obj.responseXML.getElementsByTagName( "notes" )[0].getAttribute( "savedNoteId" );
  note.element.setAttribute( "noteId", noteId );

  //lock the editor
  var editor = TinyEditor.getEditor( obj.argument + "_data" );
  editor.lock();  

  //hide the save link
  var saveLinkDiv = new YAHOO.util.Element( obj.argument + "_saveLink" );
  saveLinkDiv.setStyle( "visibility", "hidden" );

  //rebuild the index if this is the first note we're saving
  if ( OverlayManager.overlays.length == 1 ) {
    getNotebookIndex();
  }
}

function handleFailure ( obj )
{
  alert( "Problem: " + obj.statusText + " (" + obj.status + ")" ); 
}

function showSaveLink ( id )
{
  var editor = TinyEditor.getEditor( id + "_data" );
  if ( editor.hasText() ) {
    var saveLinkDiv = new YAHOO.util.Element( id + "_saveLink" );
    saveLinkDiv.setStyle( "visibility", "visible" );
  }
}

function handleTextChangedEvent ( type, args, me )
{
  showSaveLink( me );
}

function handleDragEvent ( type, args, vals )
{
  if ( args[0] == 'startDrag' ) { 
    vals[1].hide();
    TinyEditor.globalLock = true;
  }
  if ( args[0] == 'endDrag' ) {
    vals[1].show();
    showSaveLink( vals[0] ); 
    TinyEditor.globalLock = false;
  }
}

function addNotebookEntry ()
{
  newNotebookEntry( '', today, 300, 250, 50, 100, '' );
}

function newNotebookEntry ( noteId, noteDate, noteHeight, noteWidth, noteTop, noteLeft, noteContent )
{
  var name = 'note_' + index++;
  var entry = new YAHOO.widget.Panel( name, { width : noteWidth,
                                             height : noteHeight,
                                     autofillheight : "body", 
                                                  x : parseInt( noteLeft ),
                                                  y : parseInt( noteTop ),
                                constraintoviewport : false,  
                                            context : ["showbtn", "tl", "bl"],
	                                   underlay : "matte",  
	                                      close : false,  
	                                    visible : true,  
	                                  draggable : true, 
                                           dragOnly : true } ); 

  entry.setHeader("<table cellpadding='0' cellspacing='0' border='0' width='100%'><tr><td class='noteDate'>" + noteDate + "</td><td class='noteActions'><span id='" + name + "_saveLink' class='saveNoteLink'><a class='noteActionLink' href=\"javascript:saveNote( '" + name + "' )\">save</a> | </span><a class='noteActionLink' href=\"javascript:removeNote( '" + name + "' )\">delete</a></td></tr></table>");
  entry.setBody( "<textarea id='" + name + "_data' class='editor'>" + noteContent + "</textarea>" );
  entry.setFooter( '&nbsp;' );

  entry.render( "container" );

  entry.body.id = name + "_body";
  entry.body.className = "noteData";

  entry.element.setAttribute( "year", "" );
  entry.element.setAttribute( "month", "" );
  entry.element.setAttribute( "date", "" );
  entry.element.setAttribute( "noteId", noteId );

  var editor = new TinyEditor( name + '_data', 'include/tinyEditor_css.jsp' );
  editor.init();

  editor.textChanged.subscribe( handleTextChangedEvent, name ); 

  if ( noteId == '' ) {
    editor.focus();
    editor.unlock();
  }

  entry.dragEvent.subscribe( handleDragEvent, [ name, editor ] );

  OverlayManager.register( entry );

  var resize = new YAHOO.util.Resize( name, { 
	      handles: ['br'], 
	      proxy: true,
              autoRatio: false, 
	      minWidth: 250, 
	      minHeight: 100, 
	      useShim: true,
              status: false 
	}); 

  resize.on('resize', function(args) { 
	    var panelHeight = args.height; 
	    this.cfg.setProperty("height", panelHeight + "px"); 

            //fix to make the matte underlay resize its width
            var u = this.underlay;
            if( !YAHOO.lang.isUndefined(u) ){
              YAHOO.util.Dom.setStyle(u, "display", "none");
              overlay.moveTo( _left, _top );
              YAHOO.util.Dom.setStyle(u, "display", "block");
            }
	}, entry, true); 

  resize.on('startResize', function(args) { 
	 
	    if (this.cfg.getProperty("constraintoviewport")) { 
	        var D = YAHOO.util.Dom; 
	 
	        var clientRegion = D.getClientRegion(); 
	        var elRegion = D.getRegion(this.element); 
	 
	        resize.set("maxWidth", clientRegion.right - elRegion.left - YAHOO.widget.Overlay.VIEWPORT_OFFSET); 
	        resize.set("maxHeight", clientRegion.bottom - elRegion.top - YAHOO.widget.Overlay.VIEWPORT_OFFSET); 
	    } else { 
	        resize.set("maxWidth", null); 
	        resize.set("maxHeight", null); 
	    } 
	}, entry, true); 

  resize.on( 'resize', function (args) {
                            showSaveLink( name ); }, entry, true );
}

var months = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ];

function getMonth ( m )
{
  return months[m];
}

function formatDate ( year, month, date, time )
{
  return getMonth( month ) + " " + date + ", " + year;
}

getNotebookIndex();
getNotebookEntries();

<% GregorianCalendar cal = new GregorianCalendar(); %>

var today = formatDate( '<%= cal.get( Calendar.YEAR ) %>', '<%= cal.get( Calendar.MONTH ) %>', '<%= cal.get( Calendar.DATE ) %>', '' );

</script>

</html>
